<?php

namespace app\controller\admin;

use app\model\Category;
use app\model\Course;
use app\model\admin\User;
use app\model\Org;
use laytp\controller\Backend;
use think\facade\Config;
use laytp\library\CommonFun;
use app\service\admin\UserServiceFacade;

/**
 * 试题表
 */
class Questions extends Backend
{

    /**
     * questions模型对象
     * @var \app\model\Questions
     */
    protected $model;
	protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public function _initialize()
    {
        $this->model = new \app\model\Questions();
    }

    
    //查看和搜索列表
    public function index(){
        $where  = $this->buildSearchParams();
        $order  = $this->buildOrder();

        $orgId = UserServiceFacade::getUser()->org_id;
        if (!in_array($orgId, $this->allAllowOrgIds))
        {
            $where['org_id'] = $orgId;
        }

        $data   = $this->model->where($where)->order($order);
        $paging = $this->request->param('paging', false);
        if ($paging) {
            $limit        = $this->request->param('limit', Config::get('paginate.limit'));
            $data         = $data->paginate($limit)->toArray();
            $data['data'] = $this->getSelectedData($data['data']);
        } else {
            $data = $data->select()->toArray();
        }


        $adminUserList = User::where('status', ">=", '0')->column('nickname', 'id');
        $courseList = Course::where('status', ">=", "0")->column('name', 'id');
        $orgList = Org::where('status', '=', 1)->column('name', 'id');
        $categoryList = Category::where('status', ">=", "0")->column('name', 'id');
//        echo "<pre>";var_dump($courseList);die;
        if (isset($data['data'])) {
            foreach ($data['data'] as &$row) {
                $row['user_name'] = $adminUserList[$row['user_id']] ?? '';
                $row['course_name'] = $courseList[$row['course_id']] ?? '';
                $row['org_name'] = $orgList[$row['org_id']] ?? '无';
                $row['category_name'] = $categoryList[$row['category_id']] ?? '';

            }
        }
        return $this->success('数据获取成功', $data);
    }

    
    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());

        $data = $this->bulidData($post);

        try {
            if ($this->model->create($data)) {
                return $this->success('添加成功', $post);
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    
    //查看详情
    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        return $this->success('获取成功', $info);
    }

    
    //编辑
    public function edit(){
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        $post = CommonFun::filterPostData($this->request->post());
		$post['user_id'] = UserServiceFacade::getUser()->id;
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        $data = $this->bulidData($post);
        unset($data['org_id']);
        try {
            $updateRes = $info->save($data);
            if ($updateRes) {
                return $this->success('编辑成功');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    
    public function importQuestionData()
    {
        // 获取上传的文件
        $file = $this->request->file('file');
        if (!$file) {
            return $this->error('未上传文件');
        }

        // 检查文件类型
        $originalName = $file->getOriginalName();
        $allowedExtensions = ['xlsx', 'xls', 'csv'];
        $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        if (!in_array($extension, $allowedExtensions)) {
            return $this->error('文件类型不支持，仅支持 xlsx, xls, csv');
        }

        // 检查文件大小
        $maxSize = 10 * 1024 * 1024; // 10MB
        if ($file->getSize() > $maxSize) {
            return $this->error('文件大小不能超过 10MB');
        }

        // 移动文件到临时目录
        $savePath = root_path() . 'public/upload/temp/' . date('Ymd') . '/'; // 使用绝对路径
        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true);
        }
        $fileName = $file->getOriginalName(); // 替换为 getOriginalName()
        $filePath = $savePath . $fileName;

        try {
            // 确保文件移动时使用正确的路径和文件名
            $file->move($savePath, $fileName);
        } catch (\Exception $e) {
            \think\facade\Log::error('文件移动失败：' . $e->getMessage()); // 记录日志
            return $this->error('文件移动失败：' . $e->getMessage());
        }

        // 读取 Excel 文件
        try {
            if (!file_exists($filePath)) {
                return $this->error('文件不存在');
            }

            // 使用 PHPExcel 加载文件
            $objPHPExcel = \PHPExcel_IOFactory::load($filePath);
            $sheet = $objPHPExcel->getActiveSheet();
            $highestRow = $sheet->getHighestRow();
            // 检查记录数
            if ($highestRow - 7 > 507) {
                unlink($filePath); // 删除临时文件
                return $this->error('文件内记录不能超过 507 行');
            }

            
            // 从第 7 行开始读取数据
            $data = [];
            for ($row = 7; $row <= $highestRow; $row++) {
                if (empty($sheet->getCellByColumnAndRow(1, $row)->getValue()))
                    continue;

                $rowData = [
                    'type' => (int)$sheet->getCellByColumnAndRow(0, $row)->getValue(),
                    'title' => $sheet->getCellByColumnAndRow(1, $row)->getValue(),
                    'option_a' => $sheet->getCellByColumnAndRow(2, $row)->getValue() ?? '',
                    'option_b' => $sheet->getCellByColumnAndRow(3, $row)->getValue() ?? '',
                    'option_c' => $sheet->getCellByColumnAndRow(4, $row)->getValue() ?? '',
                    'option_d' => $sheet->getCellByColumnAndRow(5, $row)->getValue() ?? '',
                    'option_e' => $sheet->getCellByColumnAndRow(6, $row)->getValue() ?? '',
                    'option_f' => $sheet->getCellByColumnAndRow(7, $row)->getValue() ?? '',
                    'anwser' => $sheet->getCellByColumnAndRow(8, $row)->getValue() ?? '',
                    'analysis' => $sheet->getCellByColumnAndRow(9, $row)->getValue() ?? '',
                    'score' => (int)$sheet->getCellByColumnAndRow(10, $row)->getValue() ?? 2,
                    'difficulty' => (int)$sheet->getCellByColumnAndRow(11, $row)->getValue() ?? 1,
                    'category_id' => (int)$sheet->getCellByColumnAndRow(12, $row)->getValue() ?? 0,
                    'course_id' => (int)$sheet->getCellByColumnAndRow(13, $row)->getValue() ?? 0,
                    'user_id' => UserServiceFacade::getUser()->id,
                    'org_id' => UserServiceFacade::getUser()->org_id ?? 0,
                    'status' => 1,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];

                //校验重复
                $where = [
                    'title'         => $rowData['title'],
                    'type'          => $rowData['type'],
                    'category_id'   => $rowData['category_id'],
                    'course_id'     => $rowData['course_id'],
                    'org_id'        => UserServiceFacade::getUser()->org_id,
                ];
                if($this->getQuestion($where)) {
                    continue;
                }

                $data[] = $rowData;

            }

//            var_dump($data);die;
            // 批量插入数据
            $result = $this->model->saveAll($data);
            if ($result) {
                unlink($filePath); // 删除临时文件
                return $this->success('导入成功', ['count' => count($data)]);
            } else {
                unlink($filePath); // 删除临时文件
                return $this->error('导入失败');
            }
        } catch (\Exception $e) {
            unlink($filePath); // 删除临时文件
            \think\facade\Log::error('文件读取失败：' . $e->getMessage()); // 记录日志
            return $this->error('文件读取失败：' . $e->getMessage());
        }
    }
    
    //设置状态 0禁用 1启用
    public function setStatus()
    {
        $id       = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['status'] = $fieldVal;
        try {
            if($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }

            if ($updateRes) {
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->error('数据库异常，操作失败');
        }
    }

    public function getQuestion($where = [])
    {
        $where['status'] = 1;
        $res = $this->model->where($where)->find();
        return $res;
    }

    public function bulidData($post)
    {

        $data = [
            'type' => $post['type'],
            'title' => $post['title'],
            'anwser' => $post['anwser'],
            'socre' => $post['socre'],
            'category_id' => $post['category_id'],
            'course_id' => $post['course_id'],
            'status' => $post['status'],
            'difficulty' => $post['difficulty'],
            'user_id'   => UserServiceFacade::getUser()->id,
            'org_id'    => UserServiceFacade::getUser()->org_id
        ];


        if ($post['type'] == 1) {
            $data['option_a'] = $post['single_options_a'];
            $data['option_b'] = $post['single_options_b'];
            $data['option_c'] = $post['single_options_c'];
            $data['option_d'] = $post['single_options_d'];
            $data['anwser']   = $post['single_anwser'];
        } elseif ($post['type'] == 2) {
            $data['option_a'] = $post['multiple_options_a'];
            $data['option_b'] = $post['multiple_options_b'];
            $data['option_c'] = $post['multiple_options_c'];
            $data['option_d'] = $post['multiple_options_d'];
            $data['option_e'] = $post['multiple_options_e'];
            $data['option_f'] = $post['multiple_options_f'];
            $data['anwser']   = $post['multiple_anwser'];
        } elseif ($post['type'] == 3) {
            $data['option_a'] = $post['panduan_options_a'];
            $data['option_b'] = $post['panduan_options_b'];
            $data['anwser']   = $post['panduan_anwser'];

        }

        return $data;
    }
}
